package com.itlaoqi.rabbitmq.springboot;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.amqp.rabbit.support.RabbitExceptionTranslator;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;

@Component
public class MessageProducer {

    @Resource
    private RabbitTemplate rabbitTemplate;

    private RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {
        @Override
        //1.消息的附加信息，自定义id
        //2.代表消息是否被broke接受，true，接受，false 拒收
        //3.拒收，原因
        public void confirm(CorrelationData correlationData, boolean isAck, String cause) {
            System.out.println(correlationData);
            System.out.println("ack" + isAck);
            if(!isAck){
                System.err.println(cause);
            }
        }
    };

    private RabbitTemplate.ReturnCallback returnCallback = new RabbitTemplate.ReturnCallback() {
        @Override
        //退出消息
        //错误编码
        //错误描述
        //交换机名称等
        //路由信息
        public void returnedMessage(Message message, int replycode, String replyText, String exchange, String routingKey) {
            System.out.println("code::" + replycode + ";Text::" + replyText);
            System.out.println("Exchange::" + exchange + ";routingKey::" + routingKey);
        }
    };

    public void sendMsg(Employee emp){
        //作为消息的附加信息传递，通常是我们将他作为自定义ID
        CorrelationData cd = new CorrelationData(emp.getEmpno() + "-" + new Date().getTime());
        rabbitTemplate.setConfirmCallback(confirmCallback);
        rabbitTemplate.setReturnCallback(returnCallback);
        rabbitTemplate.convertAndSend("springboot-exchange","hr.employee",emp,cd);
    }
}
